var constant = require('../config/constant');
var User = require('../models/User');
var jwt = require('jwt-simple');
var Utils = require('./Utils');
module.exports = function(passport, nev){
	var exports = {
		checkUserAvail: function(req, res, next){
			User.findOne({username:req.param('username')},function(err,user){
				if(err){return next(err);}
				if(user){
					res.json({
						status: constant.failStatus,
						desc: constant.usernameAlreadyExit
					});
				}else{
					res.json({
						status: constant.successStatus
					});
				}
			});
		},
		signIn: function(req, res, next){
			passport.authenticate('local-signIn', { "session": false }, function(err, user, info){
				if (err) { return next(err); }
		    	if (!user) {
		    		var failResult = {};
		    		failResult.status = constant.failStatus;
		    		failResult.desc = info.desc;
		    		return res.json(failResult);
		    	}else{
		    		var succResult = {};
		    		succResult.status = constant.successStatus;
		    		succResult.desc = info.desc;
		    		var payload = {};
		    		payload.id = user.id;
		    		payload.exp = Date.now() + constant.expDuring;
		    		succResult.token = jwt.encode(payload, constant.secret);
		    		succResult.id = user.id;
		    		return res.json(succResult);
		    	}
			})(req, res, next);
		},
		signUp: function(req, res, next){
			passport.authenticate('local-signUp', { "session": false }, function(err, user, info){
				if (err) { return next(err); }
		    	if (!user) {
		    		var failResult = {};
		    		failResult.status = constant.failStatus;
		    		failResult.desc = info.desc;
		    		return res.json(failResult);
		    	}else{
		    		nev.createTempUser(user, function(newTempUser) {
			            // new user created
			            if (newTempUser) {
			                nev.registerTempUser(newTempUser);

			                var succResult = {};
				    		succResult.status = constant.successStatus;
				    		succResult.desc = constant.signUpSuccDesc;
				    		return res.json(succResult);
			            // user already exists in temporary collection!
			            } else {
			            	var succResult = {};
				    		succResult.status = constant.failStatus;
				    		succResult.desc = constant.userAleadySignup;
				    		return res.json(succResult);
			            }
			        });
		    	}
			})(req, res, next);
		},
		verifyEmail: function(req, res, next){
			var url = req.params.URL;

		    nev.confirmTempUser(url, function(userFound) {
		        if (userFound) {
	                res.render('emailVerified');
		        }else{
		        	res.render('emailVerifyError');
		        }
		    });
		},
		resetPwd: function(req, res, next){
			User.findOne({email:req.body.email}, function(err, user){
				if (err) { return next(err); }
		    	if (!user) {
		    		var failResult = {};
		    		failResult.status = constant.failStatus;
		    		failResult.desc = constant.emailNotRegister;
		    		return res.json(failResult);
		    	}else{
		    		var mailOptions = {
					    from: 'GLNote<glnote@glnote.com>', // sender address
					    to: user.email, // list of receivers
					    subject: 'Reset password instructions', // Subject line
					    html: constant.resetPwdemailTemplate // html body
					};
					var payload = {};
					payload.id = user.id;
					payload.exp = Date.now() + constant.resetPwdExpDuring;
					var reset_pwd_token = jwt.encode(payload, constant.resetPwdSecret);
		    		Utils.sendResetPwdEmail(mailOptions, reset_pwd_token, function(){
		    			var result = {};
		    			result.status = constant.successStatus;
		    			result.desc = constant.resetPwdMsg;
		    			res.json(result);
		    		}, function(){
		    			//TODO --- when email send failed
		    			res.json({});
		    		});
		    	}
			});
		},
		changePwd: function(req, res, next){
			passport.authenticate('jwt-reset-pwd', function(err, user, info) {
		    if (err) { return next(err); }
		    if (!user) {
		    	var result = {};
		    	result.status = constant.failStatus;
		    	result.desc = constant.userNotFound;
		    	res.json(result);
		    }else{
		    	user.password = user.genHash(req.body.password);
		    	user.save(function (err, user, numberAffected) {
				  if (err) next(err);
				  var result = {};
				  result.status = constant.successStatus;
				  result.desc = constant.pwdChangeSuccessMsg;
				  res.json(result);
				});
		    }
		    
		  })(req, res, next);
		},
		resendConfirmEmail: function(req, res, next){
			nev.resendVerificationEmail(req.body.email, function(userFound) {
			    if (userFound){
			    	var result = {};
	    			result.status = constant.successStatus;
	    			result.desc = constant.resendConfirmEmail;
	    			res.json(result);
			    }else{
			    	var result = {};
	    			result.status = constant.failStatus;
	    			result.desc = constant.userNotFound;
	    			res.json(result);
			    }
			});
		}
	}
	return exports;
};